/***************************************************************************
 *   Copyright (C) 2008, 2014 by Philipp Müller                            *
 *   philipp.mueller@gmx.de                                                *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA          *
 ***************************************************************************/

#ifndef VDRFINDSERVER_H
#define VDRFINDSERVER_H

#include <QObject>
#include <QHostAddress>
#include <QMutex>
#include <QWaitCondition>

/**
  Class to get IPAddress of server via a broadcast
  Not needed to keep in VDR class, as this is udp and only used once

        @author Philipp Müller <philipp.mueller@gmx.de>
*/

class QUdpSocket;

typedef struct _serverEntry
{
    QHostAddress hostAddress;
    QString      hostName;
    quint16      hostPort;
    quint8       hostNetworkType;
    quint32      hostProtocolVersion;
} serverEntry;

class VDRFindServer : public QObject
{
        Q_OBJECT

    public:
        VDRFindServer( QObject *parent = 0 );
        ~VDRFindServer();

        QList<serverEntry> serverList();
        bool socketEstablished();


    signals:
        void requestBroadcastDatagram();
        void messageError( const QString header, const QString message );


    private slots:
        void processPendingDatagrams();
        void broadcastDatagram();
        void endWait();


    private:
        /* reads bytes, if length > 0 it reads only length bytes otherwise it returns on CR */
        bool readString( QDataStream& in, QString& string, int length = 0 );

        QMutex             m_mutex;
        QWaitCondition     m_waitingForServerFound;

        QUdpSocket*        m_udpSocket;
        bool               m_socketEstablished;
        QList<serverEntry> m_serverList;
};

#endif // VDRFINDSERVER_H
